<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.text.DateFormat"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
    application.setAttribute("myapp","news");
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>新闻中国</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
  <style type="text/css">
    .main .class_date a.check{
      color:red;
    }
  </style>
  <script type="text/javascript" src="/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
	function check(){
		var login_username = document.getElementById("uname");
		var login_password = document.getElementById("upwd");
		if(login_username.value == ""){
			alert("用户名不能为空！请重新填入！010");
			login_username.focus();	
			return false;
		}else if(login_password.value == ""){
			alert("密码不能为空！请重新填入！");
			login_password.focus();
			return false;
		}
		return true;
	}
	
	function focusOnLogin(){
		var login_username = document.getElementById("uname");
		login_username.focus();	
	}
    $(function(){
        // 左边栏加载新闻
        loadLeftBar();
        // 中间主题新闻
        loadIndex();
    })

    function loadIndex(ntid,pageNumber,pageSize){
      ntid = ntid || 1;
      pageNumber = pageNumber || 1;
      pageSize = pageSize || 10;
      $.getJSON("/news.do?opr=getIndexNews",{"ntid":ntid,"pageNumber":pageNumber,"pageSize":pageSize},function(result){
         if(result.code == 200){
            // 显示所有主题
           $(".main .class_date").empty();
           let li = "<li>";
           $(result.data.topicList).each(function(i,topic){
             if((i+1) % 11 == 0){
                li += "</li><li>"
             }
             li += "<a href='#"+topic.tid+"' tid='"+topic.tid+"'><b>"+topic.tname+"</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>";
           })
           li += "</li>";
           $(".main .class_date").append(li);
           // 绑定主题点击事件
           $(".main .class_date a").click(function(){
             $(".main .class_date a").removeClass("check");
             $(this).addClass("check");
             loadNewsPage($(this).attr("tid"));
           })
           // 显示主题颜色
           $(".main .class_date a").removeClass("check");
           $(".main .class_date a[tid='"+ntid+"']").addClass("check");
           // 显示分页新闻信息
           loadNewsContent(result.data.newsPage);
         }

      })
    }

    function loadNewsPage(ntid,pageNumber,pageSize){
      ntid = ntid || 1;
      pageNumber = pageNumber || 1;
      pageSize = pageSize || 10;
       $.getJSON("/news.do?opr=getNewsByNtidPage",{"ntid":ntid,"pageNumber":pageNumber,"pageSize":pageSize},function(result){
          if(result.code == 200){
            loadNewsContent(result.data)
          }
       })
    }

    function loadNewsContent(data){
      // 显示该主题下的新闻
      $(".main .classlist").empty();
      if(data.count == 0){
        $(".main .classlist").append("<h6>抱歉，没有找到相关的新闻</h6>");
      }else{
        // 显示分页信息
        $(".count").html(data.count);
        $(".pageNumber").html(data.pageNumber);
        $(".pageCount").html(data.pageCount);
        // 渲染分页模块
        $(".first,.pre,.next,.end").show();
        if(data.pageNumber == 1){
          $(".first,.pre").hide();
        }
        if(data.pageNumber == data.pageCount){
          $(".next,.end").hide();
        }
        // 显示新闻信息
        $(data.data).each(function(i,news){
          $(".main .classlist").append(
                  "<li>"+
                  "<a href='/news.do?opr=readNews&nid="+news.nid+"'>"+news.ntitle+"</a>"+
                  "<span>"+showTime(news.ncreatedate)+"</span>"+
                  "</li>");
        })
      }
    }

    // 分页控制
    function changePage(opr){
      let tid = $(".main .class_date a[class=check]").attr("tid");
      if(opr == 1){
        loadIndex(tid,1);
      }else if(opr == -1){
        loadIndex(tid,$(".pageCount").html());
      }else if(opr == '-'){
        let number = $(".pageNumber").html()-1;
        loadIndex(tid,number);
      }else if(opr == '+'){
        let number = parseInt($(".pageNumber").html())+1;
        loadIndex(tid,number);
      }
    }
    function showTime(time){
      let now = new Date(time);
      let year = now.getFullYear();
      let month = timeFormat(now.getMonth()+1);
      let day = timeFormat(now.getDate());
      let hour = timeFormat(now.getHours());
      let minute = timeFormat(now.getMinutes());
      let second = timeFormat(now.getSeconds());
      return year + "-" + month + "-" + day
              + " " + hour + ":" + minute + ":" + second;
    }

    function timeFormat(val){
      return val < 10 ? "0"+val : val;
    }
    function loadLeftBar(){
      let json = [{"ntid":1,"pageSize":5},{"ntid":2,"pageSize":5},{"ntid":5,"pageSize":5}];
      $(json).each(function(i,e){
        $.getJSON("/news.do?opr=getNewsByNtidTop",{"ntid":e.ntid,"pageSize":e.pageSize},function (result){
          $(".sidebar .side_list:nth-of-type("+(i+1)+")").find("ul").empty();
          if(result.code == 200){
            $(result.data).each(function (j,o){
              $(".sidebar .side_list:nth-of-type("+(i+1)+")").find("ul").append("<li><a href='#"+o.nid+"'><b>"+o.ntitle+"</b></a></li>");
            })
          }
        })
      })
    }
</script>
</head>
<%!
   String username = "";
   String password = "";
%>
<%
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
       for(Cookie cookie : cookies){
          String name = cookie.getName();
          String value = cookie.getValue();
          //System.out.println(name+"="+value);
         if("loginUsername".equals(name)){
           username = value;
         }
         if("loginUserpwd".equals(name)){
           password = value;
         }
       }
    }
%>
<body onload="">

<div id="header">
    <div>在线人数：${fn:length(onlineUsers)}</div>
    <ol>
        <c:forEach var="entry" items="${onlineUsers}">
            <li>${entry.value.uname} &nbsp;&nbsp;&nbsp; ${entry.value.uroleName}</li>
        </c:forEach>
    </ol>
  <div id="top_login">
    <c:choose>
      <c:when test="${loginUser != null}">
          <label>${loginUser.uname}</label>
          <label>${loginUser.uroleName}</label>
          <label>${loginUser.ip}</label>
          <a href="/users.do?opr=loginOut">注销</a>
      </c:when>
      <c:otherwise>
          <form action="/users.do" method="post" onsubmit="return check()">
            <input type="hidden" name="opr" value="login"/>
            <label> 登录名 </label>
            <input type="text" id="uname" name="uname" value="<%=username%>" class="login_input" />
            <label> 密&#160;&#160;码 </label>
            <input type="password" id="upwd"  name="upwd" value="<%=password%>" class="login_input" />
            <input type="checkbox" name="reName" value="1" checked>
            记住密码
            <input type="submit" class="login_sub" value="登录" />
            <label id="error">${loginError}</label>
            <img src="images/friend_logo.gif" alt="Google" id="friend_logo" />
          </form>
      </c:otherwise>
    </c:choose>
  </div>
  <div id="nav">
    <div id="logo"> <img src="images/logo.jpg" alt="新闻中国" /> </div>
    <div id="a_b01"> <img src="images/a_b01.gif" alt="" /> </div>
    <!--mainnav end-->
  </div>
</div>
<div id="container">

<%@ include file="index-elements/index_sidebar.jsp"%>
 
  <div class="main">
    <div class="class_type"> <img src="images/class_type.gif" alt="新闻中心" /> </div>
    <div class="content">
      <ul class="class_date">
      <c:forEach items="${requestScope.list}" var="topic" varStatus="i">
        <c:if test="${i.count % 11 == 1}"><li id='class_month'></c:if>
        <a href="util/news?opr=listTitle&tid=${topic.tid}"><b>${topic.tname}</b></a>
        <c:if test="${i.count % 11 == 0}"></li></c:if>
        <c:set var="n" value="${i.count}"/>
      </c:forEach>
      <c:if test="${n % 11 != 0}"></li></c:if>
      </ul>
      <ul class="classlist">
      <c:choose>
        <c:when test="${requestScope.list4 == null}"><h6>出现错误，请稍后再试或与管理员联系</h6></c:when>
        <c:when test="${empty requestScope.list4}"><h6>抱歉，没有找到相关的新闻</h6></c:when>
        <c:otherwise>
          <c:forEach items="${requestScope.list4}" var="news" varStatus="i">
            <li>
            <a href='util/news?opr=readNew&nid=${news.nid}'>${news.ntitle}</a>
            <span><fmt:formatDate value="${news.ncreatedate}" pattern="yyyy-MM-dd HH:mm:ss"/></span>
            </li>
            <c:if test="${i.count % 5 == 0}"><li class='space'></li></c:if>
          </c:forEach>
        </c:otherwise>
      </c:choose>
     <%-- <p align="center"> 当前页数:[${pageIndex}/${totalPages}]&nbsp;
      <c:if test="${pageIndex > 1}">   
          <a href="util/news?opr=listTitle&pageIndex=1">首页</a>&nbsp;
          <a href="util/news?opr=listTitle&pageIndex=${pageIndex - 1}">上一页</a>
      </c:if>
      <c:if test="${pageIndex < totalPages}">
          <a href="util/news?opr=listTitle&pageIndex=${pageIndex + 1}">下一页</a>
          <a href="util/news?opr=listTitle&pageIndex=${totalPages}">末页</a> 
      </c:if></p>--%>

      </ul>
      <p> 当前页数:[<span class="pageNumber">1</span>/<span class="pageCount">1</span>]&nbsp;
        总数量:<span class="count"></span>
        <span class="first" onclick="changePage(1)">首页</span>
        <span class="pre" onclick="changePage('-')">上一页</span>
        <span class="next" onclick="changePage('+')">下一页</span>
        <span class="end" onclick="changePage(-1)">末尾</span>
      </p>
    </div>
    <%@ include file="index-elements/index_rightbar.html"%>
  </div>
</div>
  <%@ include file="index-elements/index_bottom.html"%>
</body>
</html>